package org.ccay.core.util;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.IOUtils;
import org.ccay.core.log.CcayLoggerFactory;
import org.ccay.core.log.ILogger;

/**
 * 流工具
 */
public final class StreamUtil {
	/**
	 * 流输出缓存大小
	 */
	public static final int STREAM_BUFFER_SIZE = 8*1024;
	private static final ILogger log = CcayLoggerFactory.getLogger(StreamUtil.class);
	private StreamUtil(){
	}
	/**
	 * 关闭存在的流
	 * @param streams
	 */
	public static void closeStreams(Closeable... streams) {
		for (Closeable stream : streams) {
			try {
				stream.close();
			} catch (IOException ex) {
				log.trace(ex.toString());
			} catch (RuntimeException ex) {
				log.trace(ex.toString());
			}
		}
	}
	
	/** 将输入流转向到输出流，并关闭流
	 * @param input 输入流
	 * @param output 输出流
	 * @throws IOException 
	 */
	public static void transfer(InputStream input,OutputStream output) throws IOException{
			
		
		try{
			if(input == null || output == null){
				return ;
			}
			
			IOUtils.copy(input, output);
		}finally{
			StreamUtil.closeStreams(input,output);
		}
	}
	
	/**
	 * 将输入流转向到输出流
	 * @param input 输入流
	 * @param output output
	 * @param close 使用完是否关闭
	 * @throws IOException
	 */
	public static void transfer(InputStream input,OutputStream output,boolean close) throws IOException{
		if(close){
			transfer(input,output);
			return;
		}
		if(input == null || output == null){
			return ;
		}
		IOUtils.copy(input, output);
	}
	
	/** 
	 * 流转换为字符串
	 * @param is
	 * @return
	 * @throws IOException
	 */
	public static String getSteamString(InputStream is) throws IOException {
		int i = -1;
		byte[] b = new byte[1024];
		StringBuffer sb = new StringBuffer();
		while ((i = is.read(b)) != -1) {
			sb.append(new String(b, 0, i));
		}
		return sb.toString();
	}
	
}
